<template>
  <el-card class="page-container">
    <template #header>
      <div class="header" style="text-align: center; font-weight: bold;">
        <span>我的预约</span>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline ref="searchFormRef" :model="searchData" style="display: flex; align-items: center;">
      <div style="display: flex; align-items: center;">
        <el-form-item label="会议室：" prop="roomname">
          <el-input v-model="searchData.roomname" placeholder="请输入会议室名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="state">
          <el-select v-model="searchData.state" placeholder="请选择状态" clearable>
            <el-option label="已批准" value="已批准"></el-option>
            <el-option label="待审批" value="待审批"></el-option>
            <el-option label="不批准" value="不批准"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div style="margin-left: auto;">
        <el-button type="primary" @click="fetchBookings">搜索</el-button>
        <el-button @click="resetForm(searchFormRef)">重置</el-button>
      </div>
    </el-form>

    <!-- 会议室列表 -->
    <el-table :data="bookings" style="width: 100%; text-align: center;">
      <el-table-column label="预约ID" prop="id" width="80px" align="center"></el-table-column>
      <el-table-column label="会议室名称" prop="roomname" align="center"></el-table-column>
      <el-table-column label="开始时间" prop="startTime" align="center"></el-table-column>
      <el-table-column label="结束时间" prop="endTime" align="center"></el-table-column>
      <el-table-column label="状态" prop="state" align="center">
        <template #default="{ row }">
          <el-tag :type="row.state === '已批准' ? 'success' : row.state === '不批准' ? 'danger' : 'warning'">
            {{ row.state }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拒绝原因" prop="rejectReason" align="center">
        <template #default="{ row }">
          <span v-if="row.state === '不批准'" style="color: #F56C6C;">{{ row.rejectReason || '无' }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100px" align="center">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="deleteBooking(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      :current-page="pageNum"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @update:current-page="onCurrentChange"
      @update:page-size="onSizeChange"
      style="margin-top: 20px; justify-content: center;"
    />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getUserBookingsService, deleteRoomBookService } from '@/api/book.js';
import { ElMessage } from 'element-plus';
import useUserInfoStore from '@/stores/userInfo.js';

const userInfoStore = useUserInfoStore();
const bookings = ref([]);
const searchData = ref({
  roomname: '',
  state: ''
});

const searchFormRef = ref();
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  // 重置后重新获取数据
  fetchBookings();
};

const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

const onSizeChange = (size) => {
  pageSize.value = size;
  fetchBookings();
};

const onCurrentChange = (num) => {
  pageNum.value = num;
  fetchBookings();
};

const fetchBookings = async () => {
  try {
    const result = await getUserBookingsService({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      roomname: (searchData.value.roomname || '').trim() || null,
      state: searchData.value.state || null
    });
    console.log('API Response:', result);
    if (result && result.data) {
      bookings.value = result.data || [];
      total.value = result.data.length || 0;
    } else {
      bookings.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('Error fetching bookings:', error);
    ElMessage.error('获取预约记录失败');
    bookings.value = [];
    total.value = 0;
  }
};

const deleteBooking = async (id) => {
  try {
    const result = await deleteRoomBookService(id);
    if (result?.code === 0) {
      ElMessage.success('删除成功');
      fetchBookings(); // 刷新列表
    } else {
      ElMessage.error(result?.msg || '删除失败');
    }
  } catch (error) {
    console.error('Error deleting booking:', error);
    ElMessage.error('删除失败');
  }
};

onMounted(() => {
  fetchBookings();
});
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  :deep(.el-input) {
    width: 200px;
  }

  :deep(.el-select) {
    width: 200px;
  }
}

.el-pagination__jump .el-input {
  width: 60px; /* Adjust the width as needed */
}
</style>